#include <stdio.h>
#include <string.h>
// The for loop is used to calculate the factorial of integer n
long NumofRabbits(int n);
// The recursion is used to calculate the factorial of integer n
long FactorialRecursion(int n);
// The main function
int main(void)
{
	long res;
	char inputStr[100] = "";
	do
	{
		printf("Please input an integer or a command string\n");
		scanf("%s", inputStr);
		int n = atoi(inputStr);
		/*C 库函数 int atoi(const char *str) 把参数 str 所指向的字符串转换为一个整数（类型为 int 型）。
		该函数返回转换后的长整数，如果没有执行有效的转换，则返回零。*/
		printf("The for loop is used to calculate the factorial of integer %d\n", n);
		res = NumofRabbits(n);
		printf("The result is %ld\n", res);
		printf("\nThe recursion is used to calculate the factorial of integer %d\n", n);
		res = FactorialRecursion(n);
		printf("The result is %ld\n", res);
	} while (strcmp(inputStr, "exit") != 0);

	return (0);
}

// The for loop is used to calculate the factorial of integer n
long NumofRabbits(int n)
{
	long f = 0;
	if (n < 0)
	{
		printf("input  error\n");
		f = -1;
	}
	else if (n == 0 || n == 1)
	{
		f = 1;
	}
	else
	{
		f = 1;
		int i;
		for (i = 1; i <= n; i++)
		{
			f = f * i;
		}
	}
	return f;
}

// The recursion is used to calculate the factorial of integer n
long FactorialRecursion(int n)
{
	static int count = 1; // used for counting the calling in recursion function
	/*静态局部变量使static修饰符定义，即使在声明时未赋初值，编译器也会把它初始化为0。
	且静态局部变量存储于进程的全局数据区，即使函数返回，它的值也会保持不变。
	静态局部变量的效果跟全局变量类似，但是位于函数体内部，就极有利于程序的模块化了。*/
	printf("%d-th revoke this function! \n", count++);
	long f;
	if (n < 0)
	{
		printf("input  error\n");
		f = -1;
	}
	else if (n == 0 || n == 1)
	{
		f = 1;
	}
	else
	{
		f = FactorialRecursion(n - 1) * n;
	}
	printf("%d-th revocation, return value : %ld ;\n", --count, f);
	return (f);
}


